import random

from Api.retry_model import MyRetry
from Config.config import waiwang_proxies_list
from Api.Proxy import Proxy_IP
from curl_cffi import requests as curl_requests
import my_fake_useragent as ua1

ua = ua1.UserAgent(family="chrome").random()

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.41"
}


class CRequests:
    def __init__(self):
        pass

    @MyRetry(times=5)
    def get_response(self, url, headers=None, is_proxy=None,method=None,cookies=None, error_code=[403, 429, 502]):
        if not headers:
            headers = {"user-agent": str(ua)}
        proxy = None
        if is_proxy == "Short":
            proxy = Proxy_IP.get_proxy()
        elif is_proxy == 'WaiWang':
            proxy = random.choice(waiwang_proxies_list)
        elif is_proxy == 'None':
            pass
        elif is_proxy == 'GaoXiao':
            pass
        else:
            proxies = is_proxy
        if proxy:
            response = curl_requests.get(url, headers=headers, impersonate="chrome110", proxies=proxy, allow_redirects=True, verify=False)
        else:
            response = curl_requests.get(url, headers=headers, impersonate="chrome110", allow_redirects=True, verify=False)
        if response.status_code in error_code:
            raise ValueError(f'状态码为{response.status_code}')
        # assert response.status_code not in error_code, f'请求失败, 状态码为{response.status_code}'
        return response

    @MyRetry(times=5)
    def get_session_requests(self, home_link, url, head=None, is_proxy=None):
        S = curl_requests.Session()
        if head:
            S.headers = head
        else:
            S.headers = headers
        S.impersonate = "chrome110"
        if not is_proxy:
            S.proxies = Proxy_IP.get_proxy()
        elif is_proxy == "no":
            pass
        elif is_proxy == "waiwang":
            S.proxies = random.choice(waiwang_proxies_list)
        else:
            S.proxies = is_proxy
        S.verify = False
        S.get(home_link)
        response = S.get(url)
        # if ""
        if response.status_code == "403":
            raise ValueError(f'状态码为403')
        return response


CurlRequests = CRequests()
